<template>
  <div id="app">
    <div>
      <span>图书名称:</span>
      <input type="text" v-model="name" />
    </div>
    <div>
      <button @click="addBooks" >添加/修改</button>
    </div>
    <div>
      <table border="1" cellpadding="10" cellspacing="0">
        <thead>
          <tr>
            <th>序号</th>
            <th>图书名称</th>
            <th>创建时间</th>
            <th>操作</th>
          </tr>
        </thead>
        <books-list
        :isdel="list"
        @edname="edname"
        :isEdit='isEdit'
        :obj="item"
        v-for="item in list"
        :key="item.id"
        @del-book=getData() />
      </table>
    </div>
  </div>
</template>
<script>
import BooksList from './components/BooksList.vue'
import axios from 'axios'
import { edibooksAPI, ReBooksAPI } from './api/serach'
axios.defaults.baseURL = 'http://liufusong.top:4000/'
export default {
  components: { BooksList },
  data () {
    return {
      list: [],
      name: '',
      id: 0,
      isEdit: false
    }
  },
  created () {
    this.getData()
  },
  methods: {
    // async  getData () {
    //   const res = await axios({
    //     url: '/books'
    //   })
    //   this.list = res.data
    // },

    async  getData () {
      const res = await ReBooksAPI()
      this.list = res.data
    },
    async addBooks () {
      axios({
        url: 'books/book/' + this.name
      })
        .then(res => {
          const is = res.data.status
          if (is === 1) {
            this.isEdit = true
          } else { this.isEdit = false }

          if (is === 2 && this.isEdit === false) {
            axios({
              url: '/books',
              method: 'POST',
              data: {
                name: this.name
              }
            })
            // console.log(res)

            this.getData()
            this.name = ''
          }
        }
        )
      this.getData()
      // this.name = ''
    },
    edname (e) {
      this.isEdit = true
      this.name = e.name
      this.id = parseInt(e.id)
    }
  },
  watch: {
    async  name (newval, oldval) {
      // await axios({
      //   url: 'books/' + this.id,
      //   method: 'PUT',
      //   data: {
      //     name: newval
      //   }
      // })
      await edibooksAPI(this.id, { name: newval })
    }
  }

}
</script>
